package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
)

type RegionValue struct {
	Id    int64  `json:"id"`
	Value string `json:"value"`
}

// 获取区域信息
func GetRegionInfo(p map[string]interface{}) *models.Region {
	o := orm.NewOrm()
	region := &models.Region{}
	qs := o.QueryTable("Region")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(region)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if region.Id > 0 {
			region.LevelShow = models.RegionLevel[region.Level]
		}
	}
	return region
}

// 添加区域信息
func AddRegion(input url.Values) (int64, error) {
	o := orm.NewOrm()
	region := &models.Region{}
	parentRegion := &models.Region{}
	if _, ok := input["parent_id"]; ok {
		parentRegion.Id = utils.Atoi64(input["parent_id"][0])
		o.Read(parentRegion)
	}
	region.Parent = parentRegion
	if _, ok := input["level"]; ok {
		region.Level, _ = strconv.Atoi(input["level"][0])
	}
	if _, ok := input["name"]; ok {
		region.Name = input["name"][0]
	}
	if _, ok := input["code"]; ok {
		region.Code = input["code"][0]
	}
	return o.Insert(region)
}

// 修改区域信息
func EditRegion(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("Region").Filter("id", input["id"][0]).Update(p)
}

// 获取区域列表
func GetRegionList(p map[string]interface{}) (int64, []*models.Region) {
	var regionList []*models.Region
	o := orm.NewOrm()
	qs := o.QueryTable("Region")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["parentId"]; ok {
		qs = qs.Filter("parent_id", p["parentId"])
	}
	if _, ok := p["level"]; ok {
		qs = qs.Filter("level", p["level"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&regionList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, region := range regionList {
			region.LevelShow = models.RegionLevel[region.Level]
		}
	}
	return totalCount, regionList
}

func GetRegionListValues(regionList []*models.Region) []*RegionValue {
	data := []*RegionValue{}
	for _, region := range regionList {
		regionVal := &RegionValue{
			Id:    region.Id,
			Value: region.Name,
		}
		data = append(data, regionVal)
	}
	return data
}
